<?php
/**
 * Created by PhpStorm.
 * User: dong
 * Date: 2018/4/28
 * Time: 20:55
 */
namespace App\Services\ThirdPayments\Recharge;

use App\Lib\PaymentMap;
use App\Lib\ThirdPartyMap;
use App\Models\RechargeOrder;
use App\Services\ThirdPayments\Contracts\Actions\HtmlPrintAction;
use App\Services\ThirdPayments\Contracts\RechargeBaseAbstract;
use App\Services\ThirdPayments\Contracts\WAPable;

class HYTongPayment extends RechargeBaseAbstract implements WAPable
{
    protected $gw_pay = 'http://vip.49360vip.com/hspay/node';
    protected $gw_query = 'http://vip.49360vip.com/hspay/query';

    public function callback(array $data)
    {
        // TODO: Implement callback() method.
        if ($this->veryCallbackSign($data)) {
            if ($data['r1_Code'] == 1) {
                if ($data['r9_BType'] == 1 || $data['r9_BType'] == 2)
                    return true;
            }
        }
        return false;
    }

    public function veryCallbackSign(array $data)
    {
        // TODO: Implement veryCallbackSign() method.
        $r0_Cmd		= $data['r0_Cmd'];
        $r1_Code	= $data['r1_Code'];
        $r2_TrxId	= $data['r2_TrxId'];
        $r3_Amt		= $data['r3_Amt'];
        $r4_Cur		= $data['r4_Cur'];
        $r5_Pid		= $data['r5_Pid'];
        $r6_Order	= $data['r6_Order'];
        $r7_Uid		= $data['r7_Uid'];
        $r8_MP		= $data['r8_MP'];
        $r9_BType	= $data['r9_BType'];
        $hmac		= $data['hmac'];

        $sbOld = "";
        #加入商家ID
        $sbOld = $sbOld.$this->getMchId();
        #加入消息类型
        $sbOld = $sbOld.$r0_Cmd;
        #加入业务返回码
        $sbOld = $sbOld.$r1_Code;
        #加入交易ID
        $sbOld = $sbOld.$r2_TrxId;
        #加入交易金额
        $sbOld = $sbOld.$r3_Amt;
        #加入货币单位
        $sbOld = $sbOld.$r4_Cur;
        #加入产品Id
        $sbOld = $sbOld.$r5_Pid;
        #加入订单ID
        $sbOld = $sbOld.$r6_Order;
        #加入用户ID
        $sbOld = $sbOld.$r7_Uid;
        #加入商家扩展信息
        $sbOld = $sbOld.$r8_MP;
        #加入交易结果返回类型
        $sbOld = $sbOld.$r9_BType;

        if (strcasecmp($hmac, $this->HmacMd5($sbOld, $this->getMchKey())) == 0) return true;
        return false;
    }

    public function getOrderNoFromCallback(array $data)
    {
        // TODO: Implement getOrderNoFromCallback() method.
        return $data['r6_Order'];
    }

    public function getOrderAmtFromCallback(array $data)
    {
        // TODO: Implement getOrderAmtFromCallback() method.
        return $data['r3_Amt'];
    }

    public function getThirdNoFromCallback(array $data)
    {
        return $data['r2_TrxId'];
    }

    public function isReturnInCallback(array $data)
    {
        return $data['r9_BType'] != 2 ? true : false;
    }

    /**
     * @return mixed
     */
    public function getIdentify(): string
    {
        // TODO: Implement getIdentify() method.
        return ThirdPartyMap::HUIYOUTONG;
    }

    /**
     *  needs child to achieve
     */
    public function initPaymentMap(): array
    {
        // TODO: Implement initPaymentMap() method.
        return [
           PaymentMap::QQ =>'qqmobile',
           PaymentMap::WX =>'weixin',
           PaymentMap::ALI =>'alipay',
           PaymentMap::QQ_WAP =>'qqwap',
           PaymentMap::WX_WAP =>'wxwap',
           PaymentMap::ALI_WAP =>'alipaywap',
        ];
    }

    public function query(RechargeOrder $rechargeOrder)
    {
        // TODO: Implement query() method.
        $this->setParameter('orderNum', $rechargeOrder->plat_no);
        $this->setParameter('userId', $this->getMchId());
        $this->setParameter('key', $this->getMchKey());
        $res = curlHttp($this->getGwQuery(), $this->getParameters());
        if ($res['http_code'] == 200) {
            $body = json_decode($res['body'],true);
            if ($body['status'] == 0) {
                if ($body['result'] == 0 || $body['result'] == 4) {
                    return true;
                } elseif ($body['result'] == 2) {
                    return '正在处理';
                } else {
                    return '订单错误';
                }
            }
            return $body['result'];
        }
        return $res['body'];
    }

    public function bankHref(RechargeOrder $rechargeOrder)
    {
        // TODO: Implement bankHref() method.
    }

    public function scanCode(RechargeOrder $rechargeOrder)
    {
        // TODO: Implement scanCode() method.
        $this->initParameters($rechargeOrder);
        return new HtmlPrintAction(formPostHtml($this->getGwPay(), $this->getParameters()));
    }

    public function paySign(): string
    {
        // TODO: Implement paySign() method.
        $params = $this->getParameters();
        $signStr = "";
        foreach ($params as $key => $param) {
            $signStr .= $param;
        }
//        $signStr .= $this->getMchKey();
//        Log::info('签名数据：'. $signStr );
        return $this->HmacMd5($signStr, $this->getMchKey());

    }

    public function HmacMd5($data,$key)
    {
        // RFC 2104 HMAC implementation for php.
        // Creates an md5 HMAC.
        // Eliminates the need to install mhash to compute a HMAC
        // Hacked by Lance Rushing(NOTE: Hacked means written)

        //需要配置环境支持iconv，否则中文参数不能正常处理
        $key = iconv("GB2312","UTF-8",$key);
        $data = iconv("GB2312","UTF-8",$data);

        $b = 64; // byte length for md5
        if (strlen($key) > $b) {
            $key = pack("H*",md5($key));
        }
        $key = str_pad($key, $b, chr(0x00));
        $ipad = str_pad('', $b, chr(0x36));
        $opad = str_pad('', $b, chr(0x5c));
        $k_ipad = $key ^ $ipad ;
        $k_opad = $key ^ $opad;

        return md5($k_opad . pack("H*",md5($k_ipad . $data)));
    }

    public function querySign(): string
    {
        // TODO: Implement querySign() method.
    }

    public function showSuccess(): string
    {
        // TODO: Implement showSuccess() method.
        return 'success';
    }

    public function initParameters(RechargeOrder $rechargeOrder)
    {
        // TODO: Implement initParameters() method.
        $mchData = $rechargeOrder->order_data;
        $this->setParameter('p0_Cmd', 'Buy');
        $this->setParameter('p1_MerId', $this->getMchId());
        $this->setParameter('p2_Order', $rechargeOrder->plat_no);
        $this->setParameter('p3_Amt', $rechargeOrder->order_amt);
        $this->setParameter('p4_Cur', 'CNY');
        $this->setParameter('p5_Pid', 'Customer-Item');
        $this->setParameter('p6_Pcat', 'virtual');
        $this->setParameter('p7_Pdesc', $this->setRemark($rechargeOrder));
        $this->setParameter('p8_Url', $this->getCallbackUrl());
        $this->setParameter('pa_MP', $this->setRemark($rechargeOrder));
        $this->setParameter('pd_FrpId', $this->getPaymentMap($mchData['recharge_type']));
        $this->setParameter('pr_NeedResponse', '1');
        $this->setParameter('hmac', $this->paySign());
    }

    public function wapReq(RechargeOrder $rechargeOrder)
    {
        // TODO: Implement wapReq() method.
        $this->initParameters($rechargeOrder);
        return new HtmlPrintAction(formPostHtml($this->getGwPay(), $this->getParameters()));
    }
}